import { defineStore } from "pinia";
import { postOrderList } from "@/api/order";
import { loginApi, logoutApi } from "@/api/auth";
import { getUserInfo } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";

import { LoginData } from "@/api/auth/types";
import { UserInfo } from "@/api/user/types";
import { useStorage } from "@vueuse/core";

export const useUserStore = defineStore("user", () => {
  // state
  const userId = ref();
  const token = useStorage("accessToken", "");
  // let rechargeTotal = useStorage("rechargeTotal", 0);
  const rechargeTotal = ref<string | number>('')
  const nickname = ref("");
  const avatar = ref("");
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const perms = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限

  /**
   * 登录调用
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      loginApi(loginData)
        .then((response) => {
          const { jwt } = response.data;
          token.value = jwt.token;
          rechargePageTotal()
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  function rechargePageTotal() {
    return new Promise<void>((resolve, reject) => {
      postOrderList({
        is_read: '1',
        page: 1,
        ps: 1,
        scene: "1"
      }).then((response) => {

        rechargeTotal.value = response.data.total
        resolve();
      })
        .catch((error) => {
          console.log(error)
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      getUserInfo({ with_route: 1 })
        .then(({ data }) => {

          if (!data) {
            return reject("Verification failed, please Login again.");
          }
          if (!data.power.routes || data.power.routes.length <= 0) {
            reject("getUserInfo: roles must be a non-null array!");
          }
          nickname.value = data.info.nickname;

          roles.value = data.power.routes.map((item: any) => {
            if (item.type == 1) {
              return item.path
            }
          }).filter((item: any) => item !== undefined);

          perms.value = data.power.routes.map((item: any) => {
            if (item.type != 1) {
              return item.path
            }
          }).filter((item: any) => item !== undefined);

          resolve(data.power);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 注销
  function logout() {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          resetRouter();
          resetToken();
          location.reload(); // 清空路由
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 重置
  function resetToken() {
    token.value = "";
    nickname.value = "";
    avatar.value = "";
    roles.value = [];
    perms.value = [];
  }
  return {
    token,
    nickname,
    avatar,
    roles,
    perms,
    login,
    getInfo,
    logout,
    resetToken,
    rechargeTotal,
    /**
     * 当前登录用户ID
     */
    userId,
    rechargePageTotal
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
